/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mindorks.demo;

import com.google.gson.Gson;
import com.mindorks.demo.bean.FeedDataBean;
import com.mindorks.placeholderview.LoadImageInstance;
import com.mindorks.placeholderview.Utils;
import com.mindorks.placeholderview.bean.ExpandableBean;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * FeedTestAbility
 *
 * @since 2021-05-27
 */
public class FeedTestAbility extends Ability {
    private List<ExpandableBean> mFeedList;
    private DirectionalLayout mFeedDireLayout;
    private List mItemList;
    private LoadImageInstance mLoadImageInstance;
    private List<DirectionalLayout> mDireLayoutList = new ArrayList<>();
    private List<Image> mImageList = new ArrayList<>();
    private AnimatorValue animatorValue;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_feed);

        initData();
        initView();
    }

    private void initData() {
        mFeedList = Utils.loadFeedTestData(this);
        getFeedDataList();
        mLoadImageInstance = LoadImageInstance.getInstance(this);
    }

    private void initView() {
        mFeedDireLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_feed_dire_layout);

        for (int i = 0; i < mFeedList.size(); i++) {
            Component cpt = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_item_feed_test, null, false);
            final int ii = i;
            cpt.findComponentById(ResourceTable.Id_item_depen_layout).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    setClickListener(cpt, ii);
                }
            });
            Text titleTex = ((Text) cpt.findComponentById(ResourceTable.Id_item_ex_title));
            titleTex.setText(mFeedList.get(i).getCatergory());
            try {
                titleTex.setTextColor(new Color(getResourceManager().getElement(ResourceTable.Color_white).getColor()));
            } catch (IOException e) {
                e.fillInStackTrace();
            } catch (NotExistException e) {
                e.fillInStackTrace();
            } catch (WrongTypeException e) {
                e.fillInStackTrace();
            }

            Image icon = (Image) cpt.findComponentById(ResourceTable.Id_item_ex_icon);
            DirectionalLayout exLayout = (DirectionalLayout) cpt.findComponentById(ResourceTable.Id_item_ex_layout);
            mItemList = mFeedList.get(i).getData();
            for (int j = 0; j < mItemList.size(); j++) {
                Component feedCpt = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_item_feed, null, false);
                ((Text) feedCpt.findComponentById(ResourceTable.Id_feed_title)).setText(((FeedDataBean) mItemList.get(j)).getTitle());
                ((Text) feedCpt.findComponentById(ResourceTable.Id_feed_content)).setText(((FeedDataBean) mItemList.get(j)).getCaption());
                ((Text) feedCpt.findComponentById(ResourceTable.Id_feed_time)).setText(((FeedDataBean) mItemList.get(j)).getTime());
                Image icon1 = (Image) feedCpt.findComponentById(ResourceTable.Id_feed_icon);
                ShapeElement shapeElement = new ShapeElement();
                shapeElement.setCornerRadiiArray(new float[]{20, 20, 20, 20, 20, 20, 20, 20});
                shapeElement.setRgbColor(new RgbColor(255, 255, 255));
                icon1.setBackground(shapeElement);

                WeakReference<Image> imageWeakReference = new WeakReference<Image>(icon1);
                mLoadImageInstance.loadImageFromUrlAsync(imageWeakReference, ((FeedDataBean) mItemList.get(j)).getImage_url());

                if (i == mItemList.size() - 1) {
                    feedCpt.findComponentById(ResourceTable.Id_feed_line).setVisibility(Component.HIDE);
                }
                exLayout.addComponent(feedCpt);
            }
            mDireLayoutList.add(exLayout);
            mImageList.add(icon);
            mFeedDireLayout.addComponent(cpt);
        }
    }

    private void setClickListener(Component cpt, int ii) {
        if (animatorValue != null && animatorValue.isRunning()){
            return;
        }
        int p = -1;
        for (int j = 0; j < mFeedList.size(); j++) {
            if (mFeedList.get(j).isSel()) {
                p = j;
            }
        }
        if (p != -1 && p != ii) {
            mFeedList.get(p).setSel(false);
            mImageList.get(p).setPixelMap(ResourceTable.Media_ic_keyboard_arrow_up_white);
        }

        mFeedList.get(ii).setSel(!mFeedList.get(ii).isSel());

        DirectionalLayout feedLC = (DirectionalLayout) cpt.findComponentById(ResourceTable.Id_item_ex_layout);
        int feedHeight = 0;
        for (int j = 0; j < feedLC.getChildCount(); j++) {
            feedHeight += feedLC.getComponentAt(j).getHeight();
        }

        final int a = feedHeight;
        final int pp = p;
        animatorValue = new AnimatorValue();
        animatorValue.setDuration(60);
        animatorValue.setDelay(0);
        animatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float v) {
                if (mFeedList.get(ii).isSel()) {
                    feedLC.setHeight((int) (a * v));
                    if (pp != -1 && pp != ii) {
                        mDireLayoutList.get(pp).setHeight((int) (mDireLayoutList.get(pp).getHeight() * (1 - v)));
                    }
                } else {
                    feedLC.setHeight((int) (a * (1 - v)));
                }
            }
        });
        animatorValue.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {
                if (mFeedList.get(ii).isSel()) {
                    mImageList.get(ii).setPixelMap(ResourceTable.Media_ic_keyboard_arrow_down_white);
                } else {
                    mImageList.get(ii).setPixelMap(ResourceTable.Media_ic_keyboard_arrow_up_white);
                }
            }

            @Override
            public void onStop(Animator animator) {

            }

            @Override
            public void onCancel(Animator animator) {

            }

            @Override
            public void onEnd(Animator animator) {

            }

            @Override
            public void onPause(Animator animator) {

            }

            @Override
            public void onResume(Animator animator) {

            }
        });
        animatorValue.start();
    }

    private void getFeedDataList() {
        for (int j = 0; j < mFeedList.size(); j++) {
            List dataList = mFeedList.get(j).getData();
            List<FeedDataBean> feedDataBeanList = new ArrayList<>();
            for (int i = 0; i < dataList.size(); i++) {
                Gson gson = new Gson();
                feedDataBeanList.add(gson.fromJson(dataList.get(i).toString(), FeedDataBean.class));
            }
            mFeedList.get(j).setData(feedDataBeanList);
        }
    }
}
